package ufpi.br.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;

import br.ufpi.persistenci.HibernateUtil;

public abstract class DAOImpl<T> {

	private Session session;
	private Class<T> persistentClass;

	protected abstract Long getIdObj(T obj);

	protected abstract void setIdObj(T obj, Long id);

	public DAOImpl(Class<T> persistentClass) {
		this.session = HibernateUtil.getSessao();
		this.persistentClass = persistentClass;
	}

	protected Session getSession() {
		if (session == null)
			throw new IllegalStateException(
					"Session has not been set on DAO before usage");
		return session;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	public void save(T obj) {
		
			Transaction t = getSession().beginTransaction();
                        // Antes tava getSession().saveOrUpdate(obj) e tava dando
                        // erro...
			getSession().merge(obj);
			t.commit();

	}

	public void delete(T obj) {
		Transaction t = getSession().beginTransaction();
		getSession().delete(obj);
		t.commit();
		// getSession().close();
	}

	public void update(T obj) {
		Transaction t = getSession().beginTransaction();
		getSession().saveOrUpdate(obj);
		t.commit();
	}

	@SuppressWarnings("unchecked")
	public T findByID(Long id) {
		// getSession().createQuery("from " + persistentClass.getSimpleName());
		return (T) getSession().load(getPersistentClass(), id);
	}

	public List<T> listAll() {
		return findByCriteria();
	}

	public int countAll() {
		return countByCriteria();
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

	protected int countByCriteria(Criterion... criterion) {
				Criteria crit = getSession().createCriteria(getPersistentClass());
		crit.setProjection(Projections.rowCount());
		for (final Criterion c : criterion) {
			crit.add(c);
		}
		return (Integer) crit.list().get(0);
	}
	

}
